package com.smart.manager.task;


import com.smart.common.annotation.TaskBean;
import com.smart.common.annotation.TaskMethod;
import com.smart.common.entities.domain.TaskResult;
import io.ebean.DB;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;

/**
 * 模拟任务 有参和无参任务模拟
 *
 * @author Administrator
 * @date 2022/09/16
 */
@Log4j2
@Component
@TaskBean
@RequiredArgsConstructor
public class CleanTask {


    /**
     * 清洁删除记录 被逻辑删除的数据3天后进行物理删除
     *
     * @return {@link TaskResult}
     */
    @TaskMethod(title = "清理逻辑删除数据")
    public synchronized TaskResult cleanRemoveRecord() {
        String sqlA = " SELECT \"X\".relname AS \"tbName\" FROM pg_class AS \"X\", pg_attribute AS \"Y\"  "
                + " WHERE \"Y\".attnum > 0 AND \"Y\".attrelid = \"X\".OID AND \"Y\".attname = 'deleted' "
                + " ORDER BY \"X\".relname ASC, \"Y\".attnum ASC ";

        StringBuilder tipsBuilder = new StringBuilder();
        DB.sqlQuery(sqlA).findEach(x -> {
            String tbName = x.getString("tbName");
            String delSql = "DELETE  from " + tbName + "  where deleted=TRUE AND update_time <=  (SELECT now() - interval '3 day') ";
            int rs = DB.sqlUpdate(delSql).execute();
            if (rs > 0) {
                tipsBuilder.append(tbName).append("删除").append(rs).append("条数据\n");
            }
        });

        String msg = tipsBuilder.length() == 0 ? "清理完成,本次无垃圾数据" : "清理完成".concat(tipsBuilder.toString());
        return new TaskResult(true, msg);

    }
}
